﻿using BigMonitoringWarningApi.Model.ApiResult;
using BigMonitoringWarningApi.Tool.Extension;
using GYCTOAManagementSystemNewApi.Controllers;
using GYCTOAManagementSystemNewApi.Model;
using GYCTOAManagementSystemNewApi.Model.Entity;
using GYCTOAManagementSystemNewApi.Model.Enum;
using GYCTOAManagementSystemNewApi.Model.Enum.PayrollForm;
using GYCTOAManagementSystemNewApi.Model.Request;
using GYCTOAManagementSystemNewApi.Model.Response;
using GYCTOAManagementSystemNewApi.Model.Tool;
using GYCTOAManagementSystemNewApi.Public;
using GYCTOAManagementSystemNewApi.Tool;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Build.Evaluation;
using Microsoft.CodeAnalysis;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.SqlServer.Server;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NuGet.Packaging;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Transactions;

namespace GYCTOAManagementSystemNewApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    //[Authorize]
    public class PayrollFormController : Controller
    {


        private readonly ILogger<Project1Controller> _logger;
        DBContext _db;
        PublicTool _publictool;


        Message message = null;
        public PayrollFormController(ILogger<Project1Controller> logger, DBContext db)
        {
            message = new Message();
            _logger = logger;
            _db = db;
            _publictool = new PublicTool(_db);
        }

        /// <summary>
        ///获取施工部位
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetConstructionPartEnum")]
        public ApiResult GetConstructionPartEnum()
        {

            var type = typeof(ConstructionPartEnum);
            var data = Enum.GetValues(type)
                       .Cast<ConstructionPartEnum>()
                       .Select(e => new GetEnumtResponse
                       {
                           Description = command.GetEnumDescription(e),
                           Value = Convert.ToInt32(e),
                       })
                       .ToList();

            return ApiResult.True(data);
        }
        /// <summary>
        ///获取施工类别
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetConstructionType")]
        public ApiResult GetConstructionType()
        {

            var type = typeof(ConstructionTypeEnum);
            var data = Enum.GetValues(type)
                       .Cast<ConstructionTypeEnum>()
                       .Select(e => new GetEnumtResponse
                       {
                           Description = command.GetEnumDescription(e),
                           Value = Convert.ToInt32(e),
                       })
                       .ToList();

            return ApiResult.True(data);
        }


        /// <summary>
        ///获取工作内容
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetPayrollFormConstructionType")]
        public ApiResult GetPayrollFormConstructionType()
        {
            var type = typeof(PayrollFormJobContentEnum);
            var data = Enum.GetValues(type)
                       .Cast<PayrollFormJobContentEnum>()
                       .Select(e => new GetEnumtResponse
                       {
                           Description = command.GetEnumDescription(e),
                           Value = Convert.ToInt32(e),
                       })
                       .ToList();

            return ApiResult.True(data);
        }

        #region 检查收方工资单是否开帐
        /// <summary>
        /// 检查收方工资单是否开帐
        /// </summary>
        /// <returns></returns>
        [HttpPost("CheckSettlement")]
        public ApiResult CheckSettlement([FromBody] CheckSettlementRequest request)
        {
            var Checksettlement = _db.PayrollForm.FirstOrDefault(x => x.SettlementNumber == request.SettlementNumber
            && x.Settlement && !x.Delete && x.ProjectId.Equals(request.ProjectId));
            if (Checksettlement != null)
            {
                return ApiResult.False($"当前年份编号{Checksettlement.PayrollNumber}已开帐，是否修改开帐订单,修改后社保数据将清除重新开帐时请重新填写.");

            }
            return ApiResult.True();
        }
        ///// <summary>
        ///// 修改已经开帐订单,请谨慎操作
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost("UpSettlement")]
        //public ApiResult UpSettlement([FromBody] CheckSettlementRequest request)
        //{
        //    var Checksettlement = _db.PayrollForm.FirstOrDefault(x => x.SettlementNumber == request.SettlementNumber
        //    && x.Settlement && !x.Delete&& x.ProjectId.Equals(request.ProjectId));
        //    if (Checksettlement == null)
        //    {
        //        return ApiResult.True();
        //    }
        //    Checksettlement.Settlement = false;
        //    var OrderInfoList = _db.FormUser.Where(x => x.FormId == Checksettlement.Id).ToList();
        //    OrderInfoList.ForEach(x =>
        //    {
        //        x.Settlement = false;
        //        x.SettlementNumber = string.Empty;
        //        //if (x.UserId == Checksettlement.PersonId)
        //        //{
        //        //    //删除对应的项目负责人财务
        //        //    x.Delete = true;
        //        //}
        //    });
        //    _db.PayrollForm.Update(Checksettlement);
        //    _db.FormUser.UpdateRange(OrderInfoList);
        //    _db.SaveChanges();
        //    return ApiResult.True();
        //} 
        ///// <summary>
        ///// 添加或修改开账
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost("SetSettlement")]
        //public async Task<ApiResult> SetSettlement([FromBody] SetSettlementRequest request)
        //{
        //    try
        //    {
        //        var settlements = _db.PayrollForm.Where(x => x.Settlement && !x.Delete).OrderBy(x => x.SettlementNumber).ToList();
        //        var Checksettlement = _db.PayrollForm.FirstOrDefault(x => x.SettlementNumber == request.SettlementNumber && x.Settlement && !x.Delete);
        //        var ChecksettlementById = _db.PayrollForm.FirstOrDefault(x => x.Id == request.OrderId);
        //        if (ChecksettlementById == null)
        //        {
        //            return ApiResult.True("未找到对应的订单");
        //        }
        //        var index = settlements.IndexOf(Checksettlement);
        //        if (settlements.Any() && Checksettlement != null)
        //        {
        //            Checksettlement.Settlement = false;
        //            string SettlementNumber = string.Empty;
        //            List<PayrollForm> UppayrollForms = new();
        //            if (ChecksettlementById.CreateTime > Checksettlement.CreateTime)
        //            {
        //                UppayrollForms = _db.PayrollForm.Where(x => x.CreateTime >= Checksettlement.CreateTime && x.CreateTime <= ChecksettlementById.CreateTime).ToList();
        //                SettlementNumber = settlements[index + 1].SettlementNumber;
        //            }
        //            else if (ChecksettlementById.CreateTime < Checksettlement.CreateTime)
        //            {
        //                UppayrollForms = _db.PayrollForm.Where(x => x.CreateTime <= Checksettlement.CreateTime && x.CreateTime >= ChecksettlementById.CreateTime).ToList();
        //                SettlementNumber = request.SettlementNumber;
        //            }

        //            else if (ChecksettlementById.CreateTime == Checksettlement.CreateTime)
        //            {
        //                var settlement = settlements[index];
        //                if (index + 1 < settlements.Count)
        //                {
        //                    settlement = settlements[index + 1];
        //                    UppayrollForms = _db.PayrollForm.Where(x => !x.Delete && x.CreateTime < settlement.CreateTime).ToList();
        //                    SettlementNumber = request.SettlementNumber;
        //                }
        //                else {
        //                    UppayrollForms = _db.PayrollForm.Where(x => !x.Delete && x.CreateTime >= settlement.CreateTime).ToList();
        //                    SettlementNumber = request.SettlementNumber;
        //                }

        //            }

        //            foreach (var item in UppayrollForms)
        //            {
        //                item.SettlementNumber = SettlementNumber;
        //                var orderInfo = _db.FormUser.Where(x => x.FormId == item.Id).ToList();
        //                orderInfo.ForEach(x =>
        //                {
        //                    x.SettlementNumber = item.SettlementNumber;
        //                });
        //                _db.FormUser.UpdateRange(orderInfo);
        //                _db.PayrollForm.Update(item);
        //                _db.SaveChanges();
        //            }
        //        }
        //        if (settlements.Count == 0 )
        //        {
        //            //第一次或开账最最新开账
        //            var financeReimbursementReims = _db.PayrollForm.Where(x => !x.Delete && x.CreateTime >= ChecksettlementById.CreateTime);
        //            foreach (var item in financeReimbursementReims)
        //            {
        //                item.SettlementNumber = request.SettlementNumber;
        //                var orderInfo = _db.FormUser.Where(x => x.FormId == item.Id).ToList();
        //                orderInfo.ForEach(x =>
        //                {
        //                    x.SettlementNumber = item.SettlementNumber;
        //                });
        //                _db.PayrollForm.Update(item);
        //                _db.FormUser.UpdateRange(orderInfo);
        //                _db.SaveChanges();
        //            }
        //        }
        //        ChecksettlementById.SettlementNumber = request.SettlementNumber;
        //        ChecksettlementById.Settlement = true;
        //        var orderInfoById = _db.FormUser.Where(x => x.FormId == ChecksettlementById.Id).ToList();
        //        orderInfoById.ForEach(x =>
        //        {
        //            x.SettlementNumber = request.SettlementNumber;
        //        });
        //        _db.FormUser.UpdateRange(orderInfoById);
        //        _db.PayrollForm.Update(ChecksettlementById);
        //        _db.SaveChanges();
        //        return ApiResult.True("修改成功");
        //    }
        //    catch (Exception e)
        //    {
        //        _logger.LogWarning(JsonConvert.SerializeObject(e));
        //        return ApiResult.True($"系统错误:{e.Message}");
        //        throw;
        //    }
        //}

        /// <summary>
        /// 项目管理年度开账；2025年7月24日弃用，将之前的批量年度开账改为单条记录单独开账
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("SetSettlement1")]
        public async Task<ApiResult> SetSettlement1([FromBody] SetSettlementRequest request)
        {
            try
            {
                using (var transaction = _db.Database.BeginTransaction())
                {
                    try
                    {
                        var payrollForms = _db.PayrollForm
                           .Where( x=> !x.Delete && x.ProjectId== request.Projectid).ToList();
                        // 获取已开账的收方单
                        var settlements = payrollForms
                            .Where(x => x.Settlement && !x.Delete)
                            .OrderByDescending(x => x.SettlementNumber)
                            .ToList();
                        //查找该年度已开账的记录
                        var Checksettlement = payrollForms
                            .FirstOrDefault(x => x.SettlementNumber == request.SettlementNumber && x.Settlement && !x.Delete);
                        //获取选中的收方单
                        var ChecksettlementById = payrollForms
                            .FirstOrDefault(x => x.Id == request.OrderId);

                        if (ChecksettlementById == null)
                        {
                            return ApiResult.False("未找到对应的收方单");
                        }
                        #region 废弃
                        //// 处理已有结算记录的情况
                        //if (settlements.Any() && Checksettlement != null)
                        //{
                        //    Checksettlement.Settlement = false;
                        //    string SettlementNumber = string.Empty;
                        //    List<PayrollForm> UppayrollForms = new();

                        //    var index = settlements.IndexOf(Checksettlement);
                        //    HandleExistingSettlement(Checksettlement, ChecksettlementById, settlements, index, request, out UppayrollForms, out SettlementNumber);

                        //    UpdateSettlementRecords(UppayrollForms, SettlementNumber, request);
                        //}

                        //// 处理第一次或最新开账的情况
                        //if (settlements.Count == 0)
                        //{
                        //    HandleFirstOrLatestSettlement(request, ChecksettlementById);
                        //}
                        #endregion

                        //如果没有开账记录
                        if (Checksettlement == null)
                        {
                            HandleUpdateNewYear(settlements, payrollForms, ChecksettlementById, request);
                        }
                        else
                        {
                            Checksettlement.Settlement = false;
                            string SettlementNumber = string.Empty;
                            List<PayrollForm> UppayrollForms = new();
                            var index = settlements.IndexOf(Checksettlement);
                            HandleExistingSettlement(Checksettlement, ChecksettlementById, settlements, index, request, out UppayrollForms, out SettlementNumber);
                            UpdateSettlementRecords(UppayrollForms, SettlementNumber, request);
                        }

                        // 更新目标记录
                        UpdateTargetRecord(request, ChecksettlementById);

                        // 提交事务
                        _db.SaveChanges();
                        transaction.Commit();

                        return ApiResult.True("修改成功");
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        _logger.LogWarning(JsonConvert.SerializeObject(ex));
                        return ApiResult.False($"系统错误: {ex.Message}");
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogWarning(JsonConvert.SerializeObject(e));
                return ApiResult.False($"系统错误: {e.Message}");
            }
        }
        /// <summary>
        /// 项目管理年度开账
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("SetSettlement")]
        public async Task<ApiResult> SetSettlement([FromBody] SetSettlementRequest request)
        {
            try
            {
                using (var transaction = _db.Database.BeginTransaction())
                {
                    try
                    {
                        //获取选中的收方单
                        var ChecksettlementById = _db.PayrollForm
                            .FirstOrDefault(x => x.Id == request.OrderId);

                        if (ChecksettlementById == null)
                        {
                            return ApiResult.False("未找到对应的收方单，请检查单据是否已删除");
                        }
                        if (ChecksettlementById.PayrollType == OrderStateEnum.WaitApprove)
                        { 
                            return ApiResult.False("该单据未通过审核，请先审核通过后再进行开账操作");
                        }

                        // 更新目标记录
                        UpdateTargetRecord(request, ChecksettlementById);

                        // 提交事务
                        _db.SaveChanges();
                        transaction.Commit();

                        return ApiResult.True("修改成功");
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        _logger.LogWarning(JsonConvert.SerializeObject(ex));
                        return ApiResult.False($"系统错误: {ex.Message}");
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogWarning(JsonConvert.SerializeObject(e));
                return ApiResult.False($"系统错误: {e.Message}");
            }
        }

        private void HandleExistingSettlement(
            PayrollForm OldChecksettlement,
            PayrollForm NewChecksettlementById,
            List<PayrollForm> settlements,
            int index,
            SetSettlementRequest request,
            out List<PayrollForm> UppayrollForms,
            out string SettlementNumber)
        {
            #region 废弃
            //UppayrollForms = new List<PayrollForm>();
            //SettlementNumber = string.Empty;

            //var payrollForms = _db.PayrollForm
            //               .Where(x => !x.Delete && x.ProjectId == request.Projectid).ToList();

            //if (ChecksettlementById.CreateTime > Checksettlement.CreateTime)
            //{
            //    UppayrollForms = payrollForms
            //        .Where(x => x.CreateTime >= Checksettlement.CreateTime && x.CreateTime <= ChecksettlementById.CreateTime)
            //        .ToList();
            //    SettlementNumber = settlements[index + 1].SettlementNumber;
            //}
            //else if (ChecksettlementById.CreateTime < Checksettlement.CreateTime)
            //{
            //    UppayrollForms = payrollForms
            //        .Where(x => x.CreateTime <= Checksettlement.CreateTime && x.CreateTime >= ChecksettlementById.CreateTime)
            //        .ToList();
            //    SettlementNumber = request.SettlementNumber;
            //}
            //else if (ChecksettlementById.CreateTime == Checksettlement.CreateTime)
            //{
            //    var settlement = settlements[index];
            //    if (index + 1 < settlements.Count)
            //    {
            //        settlement = settlements[index + 1];
            //        UppayrollForms = payrollForms
            //            .Where(x => !x.Delete && x.CreateTime < settlement.CreateTime)
            //            .ToList();
            //    }
            //    else
            //    {
            //        UppayrollForms = payrollForms
            //            .Where(x => !x.Delete && x.CreateTime >= settlement.CreateTime)
            //            .ToList();
            //    }
            //    SettlementNumber = request.SettlementNumber;
            //}
            #endregion
            int numberIndex = settlements.FindIndex(x => x.SettlementNumber.Equals(request.SettlementNumber));
            var financeReimbursementReim = _db.PayrollForm.Where(x => x.ProjectId == request.Projectid).ToList();
            if (OldChecksettlement.CreateTime > NewChecksettlementById.CreateTime)
            {
                SettlementNumber = request.SettlementNumber;
                //不是最大,也不是最小
                if (numberIndex != 0)
                {
                    UppayrollForms = financeReimbursementReim.Where(x => x.CreateTime >= NewChecksettlementById.CreateTime && x.CreateTime <= OldChecksettlement.CreateTime).ToList();
                }
                else
                {
                    UppayrollForms = financeReimbursementReim.Where(x => x.CreateTime >= NewChecksettlementById.CreateTime).ToList();
                }
            }
            else if (OldChecksettlement.CreateTime < NewChecksettlementById.CreateTime)
            {
                //最小年份
                if ((numberIndex + 1) == settlements.Count)
                {
                    int.TryParse(settlements[index].SettlementNumber, out var number);
                    throw new Exception($"当前无 ：{number - 1}年度信息，当前开账无法前移 ");
                }
                //中间,最大 年份(都是改变中间的差值)
                else
                {
                    UppayrollForms = financeReimbursementReim.Where(x => x.CreateTime < NewChecksettlementById.CreateTime && x.CreateTime >= OldChecksettlement.CreateTime).ToList();
                    //往上移动时间,需要修改的数据就变成去年的时间
                    SettlementNumber = settlements[numberIndex + 1].SettlementNumber;
                }
            }
            else
            {
                //最大年开账
                if (numberIndex == 0)
                {
                    UppayrollForms = financeReimbursementReim.Where(x => x.CreateTime >= NewChecksettlementById.CreateTime).ToList();
                    //往上移动时间,需要修改的数据就变成去年的时间
                    SettlementNumber = request.SettlementNumber;
                }
                else
                {
                    var fendingtime = settlements[numberIndex - 1].CreateTime;
                    UppayrollForms = financeReimbursementReim.Where(x => x.CreateTime >= NewChecksettlementById.CreateTime && x.CreateTime < fendingtime).ToList();
                    //往上移动时间,需要修改的数据就变成去年的时间
                    SettlementNumber = request.SettlementNumber;
                }
            }
        }
        /// <summary>
        /// 修改开账记录
        /// </summary>
        /// <param name="UppayrollForms"></param>
        /// <param name="SettlementNumber"></param>
        /// <param name="request"></param>
        private void UpdateSettlementRecords(List<PayrollForm> UppayrollForms, string SettlementNumber, SetSettlementRequest request)
        {
            foreach (var item in UppayrollForms)
            {
                if (request.OrderId == item.Id) item.Settlement = true;
                else item.Settlement = false;
                item.SettlementNumber = SettlementNumber;
                UpdateReimRule(item.Id, SettlementNumber);
                _db.PayrollForm.Update(item);
            }
        }
        private void HandleFirstOrLatestSettlement(SetSettlementRequest request, PayrollForm ChecksettlementById)
        {
            var payrollForms = _db.PayrollForm
                .Where(x => !x.Delete && x.CreateTime >= ChecksettlementById.CreateTime && x.ProjectId==request.Projectid)
                .ToList();
            foreach (var item in payrollForms)
            {
                item.SettlementNumber = request.SettlementNumber;
                UpdateReimRule(item.Id, request.SettlementNumber);
                _db.PayrollForm.Update(item);
            }
        }

        private void UpdateTargetRecord(SetSettlementRequest request, PayrollForm ChecksettlementById)
        {
            ChecksettlementById.SettlementNumber = request.SettlementNumber;
            ChecksettlementById.Settlement = true;

            var orderInfoById = _db.FormUser
                .Where(x => x.FormId == ChecksettlementById.Id)
                .ToList();

            orderInfoById.ForEach(x => x.SettlementNumber = request.SettlementNumber);
            _db.FormUser.UpdateRange(orderInfoById);
            _db.PayrollForm.Update(ChecksettlementById);
        }

        private void UpdateReimRule(int formId, string SettlementNumber)
        {
            var orderInfo = _db.FormUser
                .Where(x => x.FormId == formId)
                .ToList();

            orderInfo.ForEach(x => x.SettlementNumber = SettlementNumber);
            _db.FormUser.UpdateRange(orderInfo);
        }

        private void HandleUpdateNewYear(List<PayrollForm> Kzsj, List<PayrollForm> Finlist, PayrollForm ChecksettlementById, SetSettlementRequest request)
        {
            List<PayrollForm> UpdateDate;
            string lastYear = ChecksettlementById.SettlementNumber;
            var Yearlist = Kzsj.Select(x => Convert.ToInt32(x.SettlementNumber)).Distinct().ToList();
            Yearlist.Add(Convert.ToInt32(request.SettlementNumber));
            Yearlist.Sort();//升序
            var index = Yearlist.FindIndex(x => x == Convert.ToInt32(request.SettlementNumber));
            if (index == 0 && Yearlist.Count != 1)
            {
                var headerDate = Finlist.Where(x => x.SettlementNumber.Equals(Yearlist[index + 1].ToString()) && x.Settlement && !x.Delete).FirstOrDefault();
                UpdateDate = Finlist.Where(x => x.CreateTime >= ChecksettlementById.CreateTime && x.CreateTime < headerDate.CreateTime).ToList();
            }
            else if (index == Yearlist.Count - 1)
            {
                UpdateDate = Finlist.Where(x => x.CreateTime >= ChecksettlementById.CreateTime).ToList();
            }
            else
            {
                var headerDate = Finlist.Where(x => x.SettlementNumber.Equals(Yearlist[index + 1].ToString()) && x.Settlement && !x.Delete).FirstOrDefault();
                UpdateDate = Finlist.Where(x => x.CreateTime >= ChecksettlementById.CreateTime && x.CreateTime < headerDate.CreateTime).ToList();
            }
            UpdateSettlementRecords(UpdateDate, request.SettlementNumber, request);
        }
        #endregion



        /// <summary>
        ///添加收方工资单
        /// </summary>
        /// <returns></returns>
        [HttpPost("AddPayrollForm")]
        public async Task<ApiResult> AddPayrollForm([FromBody] AddPayrollFormRequest formData)
        {
            try
            {
                var UserId = HttpContext.User.Claims.FirstOrDefault().Value;
                var payrollForm = formData.payroll;
                ////收方单的单号必须是整数，工资单的单号是年月日
                //if (formData.payroll.PayrollFormType == PayrollFormTypeEnum.Should)
                //{
                //    if(!int.TryParse(payrollForm.PayrollNumber,out int num))
                //        return ApiResult.False("收方单的单号请填整数");
                //}
                //else {
                //    string[] formats = new string[] { "yyyyMMdd" }; // 可能的日期格式
                //    bool isDate = DateTime.TryParseExact(payrollForm.PayrollNumber, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date);
                //    if(!isDate)
                //        return ApiResult.False("生活费的单号请填年月日，如：20250724");
                //}
                //获取该项目下最大编号的记录
                var MaxNumberPayrollCount = _db.PayrollForm.Where(x => x.ProjectId == payrollForm.ProjectId && !x.Delete).Count();
                var project = _db.Project.FirstOrDefault(x => x.Id == payrollForm.ProjectId);
                if (MaxNumberPayrollCount != 0)
                {
                    var MaxNumberPayrollFormId = _db.PayrollForm.Where(x => x.ProjectId == payrollForm.ProjectId && !x.Delete).Max(x => (x.Id));
                    var MaxNumberPayrollForm = _db.PayrollForm.FirstOrDefault(x => x.ProjectId == payrollForm.ProjectId && !x.Delete && x.Id == MaxNumberPayrollFormId);
                    var maxPayrollNumber = MaxNumberPayrollForm.PayrollNumber;
                    var projectNameSX = project.ProjectNameSX;
                    if (!maxPayrollNumber.Contains("-"))
                    {
                        return ApiResult.False("已有的最新一条记录中的编号存在问题，不符合最新设定规律（项目名称首字母大写-数字），请修改后再添加！");
                    }
                    payrollForm.PayrollNumber = projectNameSX + "-" + (Convert.ToInt32(maxPayrollNumber.Split('-')[1]) + 1);
                }
                else
                {
                    payrollForm.PayrollNumber = project.ProjectNameSX + "-1";
                }
                //var MaxNumberPayrollFormId= _db.PayrollForm.Where(x => x.ProjectId == payrollForm.ProjectId &&!x.Delete).Max(x => (x.Id));
                //var MaxNumberPayrollForm = _db.PayrollForm.FirstOrDefault(x => x.ProjectId == payrollForm.ProjectId && !x.Delete && x.Id == MaxNumberPayrollFormId);
                //var project = _db.Project.FirstOrDefault(x => x.Id == payrollForm.ProjectId);
                //if (MaxNumberPayrollForm != null) {
                //    var maxPayrollNumber = MaxNumberPayrollForm.PayrollNumber;
                //    var projectNameSX= project.ProjectNameSX;
                //    if (!maxPayrollNumber.Contains("-"))
                //    {
                //        return ApiResult.False("已有的最新一条记录编号存在问题，请修改后再添加！");
                //    }
                //    payrollForm.PayrollNumber = projectNameSX+"-"+(Convert.ToInt32(maxPayrollNumber.Split('-')[1])+1);
                //}
                //else
                //{
                //    payrollForm.PayrollNumber = project.ProjectNameSX + "-1";
                //}
                List<PayrollForm> payrollForms = _db.PayrollForm.Where(x => x.ProjectId == payrollForm.ProjectId && x.PayrollNumber == payrollForm.PayrollNumber && !x.Delete).ToList();
                if (payrollForms.Count > 0)
                {
                    return ApiResult.False("已存在相同的单号，请勿重复添加");
                }
                //payrollForm.SettlementNumber = _db.PayrollForm.Where(x=>x.ProjectId == payrollForm.ProjectId).Max(x => (x.SettlementNumber));
                await _db.PayrollForm.AddAsync(payrollForm);
                await _db.SaveChangesAsync();
                formData.users.ForEach(x =>
                {
                    //x.SettlementNumber = payrollForm.SettlementNumber;
                    //x.Settlement = payrollForm.Settlement;
                    x.ConstructionType = payrollForm.ConstructionType;
                    x.ProjectCreateTime = payrollForm.CreateTime;
                    x.ProjectId = payrollForm.ProjectId;
                    x.FormId = payrollForm.Id;
                    x.FormType = formData.payroll.PayrollFormType;
                    x.PayrollType = OrderStateEnum.WaitApprove;
                    x.OperatDate = DateTime.Today;
                    x.TotalPrice = x.Price * x.WorkingDays;
                    x.OperatId = Convert.ToInt32(UserId);
                });
                await _db.FormUser.AddRangeAsync(formData.users);
                await _db.SaveChangesAsync();
                return ApiResult.True();
            }
            catch (Exception ex)
            {
                return ApiResult.False(ex.Message);
                throw;
            }
        }
        /// <summary>
        ///删除收方工资单
        /// </summary>
        /// <returns></returns>
        [HttpPost("DelPayrollForm")]
        public async Task<ApiResult> DelPayrollForm([FromBody] DataIdRequest formData)
        {
            var payrollForm = _db.PayrollForm.FirstOrDefault(x => x.Id.Equals(formData.Id));
            payrollForm.Delete = true;
            await _db.SaveChangesAsync();
            return ApiResult.True();
        }

        /// <summary>
        ///查询具体收方工资单记录
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetPayrollFormAsync")]
        public async Task<ApiResult> GetPayrollFormAsync([FromBody] GetPayrollFormAsyncRequset Data)
        {
            var PayrollFormUsers= _db.PayrollForm.Where(x => x.ProjectId.Equals(Data.ProjectId)
                    && (int)x.PayrollFormType == (int)Data.PayrollFormType); 
            if (Data.IsDelete)
            {
                PayrollFormUsers = PayrollFormUsers.Where(x => x.Delete);
            }
            else {
                PayrollFormUsers = PayrollFormUsers.Where(x => !x.Delete);
            }
            
            var tolist = PayrollFormUsers.ToList();
            //开账
            if (!string.IsNullOrWhiteSpace(Data.SettlementNumber))
            {
                PayrollFormUsers = PayrollFormUsers.Where(x => x.SettlementNumber == (Data.SettlementNumber));
            }
            else {
                //var max = PayrollFormUsers.Max(x => x.SettlementNumber);
                //PayrollFormUsers = PayrollFormUsers.Where(x => x.SettlementNumber == DateTime.Now.Year.ToString());
                
                if (Data.CreateDate != null)
                {
                    PayrollFormUsers = PayrollFormUsers.Where(x => x.CreateTime >= Data.CreateDate);
                }
                if (Data.EndDate != null)
                {
                    PayrollFormUsers = PayrollFormUsers.Where(x => x.CreateTime <= Data.EndDate);
                }
            }

            if (!string.IsNullOrWhiteSpace(Data.PayrollFormNumber))
            {
                PayrollFormUsers = PayrollFormUsers.Where(x => x.PayrollNumber.Contains(Data.PayrollFormNumber));
            }
            if (Data.Status != null)
            {
                PayrollFormUsers = PayrollFormUsers.Where(x => x.PayrollType == Data.Status);
            }
            //if (Data.CreateDate != null)
            //{
            //    PayrollFormUsers = PayrollFormUsers.Where(x => x.CreateTime >= Data.CreateDate);
            //}
            //if (Data.EndDate != null)
            //{
            //    PayrollFormUsers = PayrollFormUsers.Where(x => x.CreateTime <= Data.EndDate);
            //}
            if (Data.ConstructionType != 0)
            {
                PayrollFormUsers = PayrollFormUsers.Where(x => x.ConstructionType == Data.ConstructionType);
            }
            if (Data.PersonId != 0)
            {
                PayrollFormUsers = PayrollFormUsers.Where(x => x.PersonId == Data.PersonId);
            }
            if (Data.OrderUserId != 0)
            {
                var formlist = _db.FormUser.Where(x => x.UserId.Equals(Data.OrderUserId) && !x.Delete).Select(x => x.FormId).ToList();
                PayrollFormUsers = PayrollFormUsers.Where(x => formlist.Contains(x.Id));
            }
            var PayrollFormUserslist = PayrollFormUsers.ToList().OrderByDescending(x => x.Id).ToList();
            return ApiResult.True(PayrollFormUserslist);
        }


        /// <summary>
        ///查询具体收方工资单
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetPayrollUserAsync")]
        public ApiResult GetPayrollUserAsync([FromBody] DataIdRequest Data)
        {
            var PayrollFormUsers = _db.FormUser.Where(x => x.FormId.Equals(Data.Id) && !x.Delete).ToList();
            return ApiResult.True(PayrollFormUsers);
        }

        /// <summary>
        ///删除项目工资单人员详情
        /// </summary>
        /// <returns></returns>
        [HttpPost("DelPayrollFormUser")]
        public async Task<ApiResult> DelPayrollFormUser([FromBody] DataIdRequest payrollFormId)
        {
            var PayrollFormUsers = _db.FormUser.FirstOrDefault(x => x.Id.Equals(payrollFormId.Id));
            PayrollFormUsers.Delete = true;
            _db.Update(PayrollFormUsers);
            await _db.SaveChangesAsync();
            return ApiResult.True(PayrollFormUsers);
        }


        /// <summary>
        ///查询工资单详情
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetPayrollFormUserBy")]
        public async Task<ApiResult> GetPayrollFormUser([FromBody] DataIdRequest payrollFormId)
        {
            var PayrollFormUsers = await _db.FormUser.Where(x => x.FormId.Equals(payrollFormId.Id) && !x.Delete).ToListAsync();
            return ApiResult.True(PayrollFormUsers);
        }
        /// <summary>
        ///获取工资单号
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetPayrollFormNumber")]
        public ApiResult AddPayrollForm()
        {
            return ApiResult.True("HD_SFGZD_" + DateTime.Now.ToString("yyyyMMddHHmmss"));
        }

        /// <summary>
        /// 修改工资单状态 
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("UpPayrollForm")]
        public async Task<ApiResult> UpPayrollForm([FromBody] AddPayrollFormRequest formData)
        {
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
            var right = Convert.ToString(TokenManage.GetTokenValues(author)[2].Value);
            var project = _db.Project.FirstOrDefault(x => x.Id.Equals(formData.payroll.ProjectId));
            //最高权限直接审批
            if (!(right.Contains(PublicTool.Admin) || userid == Convert.ToInt32(project.HeadUserId)))
            {
                return ApiResult.False("您无权操作此功能");
            }
            //当前项目开帐后自动填写项目负责人的收方工资单
            if (formData.payroll.Settlement)
            {
                new FormUser()
                {
                    TotalPrice = project.Managementfee,
                    FormId = formData.payroll.Id,
                    UserId = userid,
                };
            }
            List<FormUser> users = new List<FormUser>();
            foreach (var item in formData.users)
            {
                //修改时填写开帐
                item.Settlement = formData.payroll.Settlement;
                //修改时填写开帐号
                item.SettlementNumber = formData.payroll.SettlementNumber;
                item.ConstructionType = formData.payroll.ConstructionType;
                item.ProjectId = formData.payroll.ProjectId;
                item.ProjectCreateTime = DateTime.Now;
                item.FormType = formData.payroll.PayrollFormType;
                item.TotalPrice = item.Price * item.WorkingDays;
                if (item.Id == 0)
                {
                    item.FormId = formData.payroll.Id;
                    users.Add(item);
                }
            }
            _db.PayrollForm.UpdateRange(formData.payroll);
            _db.FormUser.UpdateRange(formData.users);
            if (users.Any())
            {
                _db.FormUser.AddRange(users);
            }
            _db.SaveChanges();
            var data = _db.FormUser.Where(x => x.FormId.Equals(formData.payroll.Id) && x.PayrollType == OrderStateEnum.WaitApprove).ToList();
            if (!data.Any())
            {
                //    formData.payroll.PayrollType = OrderStateEnum.Success;
                _db.PayrollForm.UpdateRange(formData.payroll);
                _db.SaveChanges();
            }
            return ApiResult.True();
        }



        /// <summary>
        /// 最高权限人审批单据状态
        /// </summary>
        /// <param name="formData"></param> 
        /// <returns></returns>
        [HttpPost("UpPayrollTypeByAdmin")]
        public ApiResult UpPayrollTypeByAdmin([FromBody] DataFormUsersRequest Data)
        {
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var right = Convert.ToString(TokenManage.GetTokenValues(author)[2].Value);
            var project = _db.Project.FirstOrDefault(x => x.Id.Equals(Data.users.FirstOrDefault().ProjectId));
            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);

            //最高权限直接审批
            if (!(right.Contains(PublicTool.Admin) || userid == Convert.ToInt32(project.HeadUserId)))
            {
                return ApiResult.False("您无权操作此功能");
            }
            if (Data.users.Any())
            {
                Data.users.ForEach(x =>
                {
                    x.PayrollType = OrderStateEnum.Success;
                });
                _db.FormUser.UpdateRange(Data.users);
                _db.SaveChanges();
                var formId = Data.users.FirstOrDefault().FormId;
                var data = _db.FormUser.Where(x => x.FormId.Equals(formId) && x.PayrollType == OrderStateEnum.WaitApprove && !x.Delete).ToList();
                if (!data.Any())
                {
                    var payroll = _db.PayrollForm.FirstOrDefault(x => x.Id.Equals(formId));
                    payroll.PayrollType = OrderStateEnum.Success;
                    _db.PayrollForm.UpdateRange(payroll);
                    _db.SaveChanges();
                }
                return ApiResult.True();
            }
            return ApiResult.False($"请选择相关人员审批");
        }

        /// <summary>
        /// 查询人员工作时间内是否有重复的
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("UserByProjectDate")]
        public async Task<ApiResult> UserByProjectdate([FromBody] UserByProjectDateRequest userBy)
        {
            var data = _db.FormUser.Where(x => x.UserId.Equals(userBy.UserId) && x.JobCreateTime < userBy.JobEndDate && x.JobEndTime > userBy.JobStartDate && x.FormType == userBy.FormType && !x.Delete).ToList();
            var FormIds = data.Select(x => x.FormId).ToList();
            var PayrollFormdata = _db.PayrollForm.Where(x => FormIds.Contains(x.Id)).ToList();
            if (!data.Any())
            {
                return ApiResult.True();
            }

            return ApiResult.False($"当前填充的数据时间与{string.Join(",", PayrollFormdata.Select(x => x.PayrollNumber))}中的时间发生了冲突");
        }

        /// <summary>
        /// 创建收方工资单的数据内容//下在收方工资单需为完整的状态下修改
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("GetPayrollFormExcel")]
        public async Task<ApiResult> GetPayrollFormExcel([FromBody] DataIdRequest Data)
        {
            var PayrollForm = _db.PayrollForm.Where(x => x.Id.Equals(Data.Id) && !x.Delete).FirstOrDefault();
            var PayrollFormUsers = _db.FormUser.Where(x => x.FormId.Equals(PayrollForm.Id) && !x.Delete).ToList();
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userId = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
            var RoleName = Convert.ToString(TokenManage.GetTokenValues(author)[2].Value);
            var project = _db.Project.FirstOrDefault(x => x.Id.Equals(PayrollForm.ProjectId));
            if (!(userId == Convert.ToInt32(project.HeadUserId) || RoleName.Equals(PublicTool.Admin)))
            {
                return ApiResult.False("您当前无权进行下载程序");
            }
            var WaitData = new List<int>();

            PayrollFormUsers.ForEach((x) =>
            {
                if (x.PayrollType == OrderStateEnum.WaitApprove)
                {
                    WaitData.Add(x.UserId);
                }
            });
            if (WaitData.Any())
            {
                var users = _db.Users.Where(x => WaitData.Contains(x.Id)).ToList();

                return ApiResult.False($"审批单：{PayrollForm.PayrollNumber}下有:{string.Join(",", users.Select(x => x.UserName))}还未审核，请审核后再次下载");
            }
            var result = new PublicTool().CreateExcelToSFGZD(PayrollFormUsers, PayrollForm, project.ProjectName);
            return ApiResult.True(result);
        }



        /// <summary>
        /// 创建财务获取工资单的数据内容 包括收方工资单、实发工资单
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("GetPayrollusertData")]
        public async Task<ApiPageResult> GetPayrollusertData([FromBody] GetpayDataRequest Data)
        {
            try
            {
                var payrollFormUsers = from formUser in _db.FormUser
                                       join payrollForm in _db.PayrollForm on formUser.FormId equals payrollForm.Id
                                       join project in _db.Project on formUser.ProjectId equals project.Id
                                       join user in _db.Users on formUser.UserId equals user.Id
                                       where (!Data.UserId.HasValue || user.Id == Data.UserId) &&
                                             (!Data.PayrollFormType.HasValue || (int)payrollForm.PayrollFormType == (int)Data.PayrollFormType) &&
                                             (!Data.ProjectId.HasValue || project.Id == Data.ProjectId) &&
                                             (!Data.CreateTime.HasValue || formUser.JobCreateTime.Value.Date >= Data.CreateTime.Value.Date) &&
                                             (!Data.EmdTime.HasValue || formUser.JobEndTime.Value.Date <= Data.EmdTime.Value.Date)
                                       select new
                                       {
                                           ProjectName = project.ProjectName,
                                           UserName = user.UserName,
                                           formUser = formUser,
                                           PayrollFormType = payrollForm.PayrollFormType
                                       };
                var data = payrollFormUsers.OrderBy(x => x.formUser.ProjectCreateTime).ToList();
                var rows = data.Skip(Data.PageSize * (Data.PageIndex - 1)).Take(Data.PageSize).ToList();
                return ApiPageResult.True(rows, Data.PageIndex, Data.PageSize, data.Count);
            }
            catch (Exception ex)
            {
                return ApiPageResult.False(new { }, Data.PageIndex, Data.PageSize, $"程序出现问题：{ex.Message},请联系开发相关人员");
            }
        }

        /// <summary>
        /// 创建财务获取工资单的数据内容 包括收方工资单、实发工资单
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("GetPayrollusertData2")]
        public async Task<ApiPageResult> GetPayrollusertData2([FromBody] GetpayDataRequest Data)
        {
            try
            {

                IQueryable<FormUser> data = _db.FormUser.Where(x => x.PayrollType == OrderStateEnum.Success && !x.Delete);
                if (Data.UserId.HasValue)
                {
                    data = data.Where(x => x.UserId == Data.UserId);
                }
                if (Data.ProjectId.HasValue)
                {
                    data = data.Where(x => x.ProjectId == Data.ProjectId);
                }
                if (Data.CreateTime.HasValue)
                {
                    data = data.Where(x => x.JobCreateTime.Value.Date >= Data.CreateTime.Value.Date);
                }
                if (Data.EmdTime.HasValue)
                {
                    data = data.Where(x => x.JobCreateTime.Value.Date <= Data.EmdTime.Value.Date);
                }
                var datarelust = data.ToList();
                var datarelustGrop = from formUser in data.ToList()
                                     group formUser by new { formUser.ProjectId, formUser.UserId } into projectGroup
                                     select new
                                     {
                                         ProjectId = projectGroup.Key.ProjectId,
                                         UserId = projectGroup.Key.UserId,
                                         ShouldTotalPrice = projectGroup.Where(j => j.FormType == PayrollFormTypeEnum.Should).Sum(x => x.TotalPrice),
                                         RealTotalPrice = projectGroup.Where(j => j.FormType == PayrollFormTypeEnum.Real).Sum(x => x.TotalPrice),

                                     };
                var result = datarelustGrop.ToList();
                var rows = result.Skip(Data.PageSize * (Data.PageIndex - 1)).Take(Data.PageSize).ToList();
                //return ApiPageResult.False(new { }, Data.PageIndex, Data.PageSize, $"程序出现问题,请联系开发相关人员");

                return ApiPageResult.True(rows, Data.PageIndex, Data.PageSize, result.Count);
            }
            catch (Exception ex)
            {
                return ApiPageResult.False(new { }, Data.PageIndex, Data.PageSize, $"程序出现问题：{ex.Message},请联系开发相关人员");
            }
        }

        /// <summary>
        /// 根据项目Id 人员Id。开始时间、结束时间 获取具体的数据内容
        /// </summary>
        /// <param name="formData"></param>
        /// <returns></returns>
        [HttpPost("GetPayrollInfo")]
        public async Task<ApiResult> GetPayrollInfo([FromBody] GetPayrollInfoRequest Data)
        {
            try
            {
                IQueryable<FormUser> data = _db.FormUser.Where(x => x.PayrollType == OrderStateEnum.Success);
                if (Data.UserId.HasValue)
                {
                    data = data.Where(x => x.UserId == Data.UserId);
                }
                if (Data.ProjectId.HasValue)
                {
                    data = data.Where(x => x.ProjectId == Data.ProjectId);
                }
                if (Data.CreateTime.HasValue)
                {
                    data = data.Where(x => x.JobCreateTime.Value.Date >= Data.CreateTime.Value.Date);
                }
                if (Data.EmdTime.HasValue)
                {
                    data = data.Where(x => x.JobCreateTime.Value.Date <= Data.EmdTime.Value.Date);
                }
                var forms = data.ToList().GroupBy(x => x.FormId).ToList();
                List<GetPayrollInfoResponse> responses = new();
                foreach (var item in forms)
                {
                    var dataResult = new GetPayrollInfoResponse();
                    dataResult.payrollForm = _db.PayrollForm.FirstOrDefault(x => x.Id.Equals(item.Key));
                    dataResult.formUsers.AddRange(item);
                    responses.Add(dataResult);
                }
                return ApiResult.True(responses);
            }
            catch (Exception ex)
            {
                return ApiResult.False($"程序出现问题：{ex.Message},请联系开发相关人员");
            }
        }
    }
}

